<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<style type="text/css">
    .ui-datepicker-calendar {
        display: none;
    }

    .ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year {
        width: 44%;
    }

    .tablewrapper table#example {
        width: 1024px !important;
    }
</style>
<div class="panel_container">

    <div class="panel">
        <form id="form_search">
            <div class="panel_header">
                <div><h2>担保业务管理</h2></div>
            </div>

            <div class="panel_body">
                <div>
                    <div class="info_item"><span>请选择业务时间:</span>
                        <input type="text" name="query_sjsj" maxlength="10" id="sjsj"/>
                    </div>
                </div>
               <div>
                   <div class="info_item"><span>是否只显示问题记录？</span>
                       <input id="exit" type="checkbox"  />
                       <input id="existError" name="query_existError" type="hidden" value="" >
                   </div>
                   <div class="info_item"><span>是否只显示已忽略记录？</span>
                       <input id="skip" type="checkbox"  />
                       <input id="skipInd" name="skipInd" type="hidden" value="" >
                       <c:if test="${isFh=='false'}">
                           <input  name="orgId" type="hidden" value="${orgId}">
                       </c:if>
                   </div>
               </div>
                <c:if test="${isFh=='true'}">
                    <div>
                        <div class="info_item"><span>请选择业银行:</span>
                            <select name="orgId" id="orgId">
                                <option value="">--请选择--</option>
                                <c:forEach var="entry" items="${orgList}">
                                    <option value="${entry.id}" >${entry.orgName}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                </c:if>
            </div>

            <div class="panel_footer">
                <div>
                    <div class="info_item ml_1">
                        <input type="button" class="btn_blue" value="查询" id="btn_search">&nbsp;
                        <input type="button" class="btn_blue" value="导出" id="btn_export">&nbsp;
                        <%--<input id="btn_add" class="btn_blue" type="button" value="添加担保">&nbsp;--%>
                        <input id="btn_import" class="btn_blue" type="button" value="导入担保">
                    </div>
                </div>
            </div>
        </form>
    </div>

    <div class="panel">
        <div class="panel_body">
            <div>
                <table id="grid_tbl"></table>
                <div id="pager"></div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var colModelConfgiId="${config.id}";
    $(function () {
        $("#sjsj").datepicker({
            defaultDate: "+1w",
            changeYear: true,
            changeMonth: true,
            numberOfMonths: 1,
            dateFormat: "yy-mm",
            onChangeMonthYear: function (year, month, inst) {
                var selected_month = month-1;
                var selected_year = year;
                $(this).datepicker('setDate', new Date(selected_year, selected_month, 1));
            },
            beforeShow: function (input, inst) {
                if ((datestr = $(this).val()).length > 0) {
                    actDate = datestr.split('-');
                    year = actDate[0];
                    month = actDate[1] - 1;
                    $(this).datepicker('option', 'defaultDate', new Date(year, month));
                    $(this).datepicker('setDate', new Date(year, month));
                }
            }
        });

        if($('#sjsj').val()==""){
            var curDate = new Date();
            var preDate = new Date(curDate.getFullYear(),curDate.getMonth()-1,curDate.getDay());
            $('#sjsj').val(preDate.format("yyyy-MM"));
        }

    });

    function getName(){
        var params = $("#grid_tbl").jqGrid('getGridParam','colModel');
        var cols="";
        for ( var i = 0; i < params.length; i++) {
            if(!params[i].hidden && params[i].name!="cb" && params[i].name!="act" ){
                if(cols!=""){
                    cols =cols+","
                }
                cols =cols+ params[i].name;
            }
        }
        return cols
    }

    function getHiddenName(){
        var params = $("#grid_tbl").jqGrid('getGridParam','colModel');
        var cols="";
        for ( var i = 0; i < params.length; i++) {
            if(params[i].hidden && params[i].name!="cb" && params[i].name!="act" ){
                if(cols!=""){
                    cols =cols+","
                }
                cols =cols+ params[i].name;
            }
        }
        return cols
    }

    function getTitle(){
        var params = $("#grid_tbl").jqGrid('getGridParam','colModel');
        var cols="";
        for ( var i = 0; i < params.length; i++) {
            if(!params[i].hidden && params[i].name!="cb" && params[i].name!="act" ){
                if(cols!=""){
                    cols =cols+","
                }
                cols =cols+ params[i].label;
            }
        }
        return cols
    }


    function gotoAddGuarantee(){
        linkTo("${ctx}/guarantee/toAddGuarantee");
    }

    function refreshList(){
        $("#grid_tbl").jqGrid('setGridParam',{postData:$("#form_search").serializeObject()}).trigger("reloadGrid");
    }

    function exportGuarantee(){
        $.ajax({
            url:'${ctx}/file/exportExcel?d='+new Date().getTime(),
            dataType:'json',
            contentType:"application/x-www-form-urlencoded:charset=UTF-8",
            data: {sjsj: $('#sjsj').val(), existError: $('#existError').val(), skipInd: $('#skipInd').val(),title:getTitle(),name:getName,businessType:"27"},
            success:function(data){
                if (data.result = "true") {
                    window.location.href = "${ctx}/file/down?fileName=" + data.message+"&systemType=guarantee";
                } else {
                    $.prompt("下载出错");
                }
            }});
    }

    function ignoreGuarantee (ids){
        $.ajax({
            url: '${ctx}/guarantee/ignoreGuarantee?d='+new Date().getTime(),
            dataType: 'json',
            data: {ids: ids},
            success: function (data) {
                refreshList();
            }
        });
    }

    function gotoImportGuarantee(){
        linkTo("${ctx}/guarantee/toImportGuarantee");
    }

    function custom_length(value,colname,v1,length){
        if (value.length>length)
            return [false,colname+"数据长度不能超过"+length];
        else
            return [true,""];
    }

    $(function () {

        var postData=$("#form_search").serializeObject();

        $("#exit").bind("click", function () {
            if($("#exit").is(":checked")==true){
                $("#existError").val("Y")
            }else{
                $("#existError").val("")
            }
        });

        $("#skip").bind("click",function() {
            if($("#skip").is(":checked")==true){
                $("#skipInd").val("Y")
            }else{
                $("#skipInd").val("")
            }
        });

        $("#btn_add").bind("click", function(){
            gotoAddGuarantee();
        });

        $("#btn_import").bind("click", function () {
            gotoImportGuarantee();
        });

        $("#btn_search").bind("click", function(){
            refreshList();
        });

        $("#btn_export").bind("click", function(){
            exportGuarantee();
        });


        var lastsel1;
        $("#grid_tbl").jqGrid({
            datatype: "json",
            url : "${ctx}/guarantee/guaranteeList?d="+new Date().getTime(),
            mtype: "POST",
            postData: postData,
            width:"100%",
            height:"100%",
            colNames: ['id','担保机构组织机构代码','金融机构编码','数据时间','担保合同号',
                '被担保人组织机构代码','币种','担保业务种类','担保余额','担保开始日期','担保到期日期',
                '五级分类','当月代偿发生金额','当月担保发生额','当月担保发生笔数','在保笔数','错误描述', '是否错误','是否忽略'],
            colModel: [
                {name:'id',index:'id',hidden: true,label:'id'},
                {name: 'dbjgzzdm', index: 'dbjgzzdm',sortable:false,label:'担保机构组织机构代码',searchoptions:{sopt:['bw']}},
                {name: 'jrjgbm', index: 'jrjgbm',sortable:false,label:'金融机构编码',search : false},
                {name: 'sjsj', index: 'sjsj',sortable:false,label:'数据时间',search : false},
                {name: 'dbhth', index: 'dbhth',sortable:false,label:'担保合同号',searchoptions:{sopt:['bw']}},
                {name: 'bdbrzzjgdm', index: 'bdbrzzjgdm',sortable:false,editable: true,editoptions:{maxlength:10},editrules:{custom:true,custom_func:function(value,nm,v1){
                    return custom_length(value,nm,v1,10);
                }},label:'被担保人组织机构代码',searchoptions:{sopt:['bw']}},
                {name: 'bz', index: 'bz',sortable:false,label:'币种',searchoptions:{sopt:['eq']},
                    formatter:function(cellvalue, options, rowObject){
                        return rowObject.bzDesc;
                    }
                },
                {name: 'dbywzl', index: 'dbywzl',sortable:false,label:'担保业务种类',searchoptions:{sopt:['eq']},
                    formatter:function(cellvalue, options, rowObject){
                        return rowObject.dbywzlDesc;
                    }
                },
                {name: 'dbye', index: 'dbye',sortable:false,label:'担保余额',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'dbksrq', index: 'dbksrq',sortable:false,label:'担保开始日期',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'dbdqrq', index: 'dbdqrq',sortable:false,label:'担保到期日期',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'wjfl', index: 'wjfl',sortable:false,label:'五级分类',searchoptions:{sopt:['eq']},
                    formatter:function(cellvalue, options, rowObject){
                        return rowObject.wjflDesc;
                    }
                },
                {name: 'dydcfsje', index: 'dydcfsje',sortable:false,editable: true,editrules:{number:true,maxValue:9999999999999.99},label:'当月代偿发生金额',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'dydbfsje', index: 'dydbfsje',sortable:false,label:'当月担保发生额',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'dyfsbs', index: 'dyfsbs',sortable:false,label:'当月担保发生笔数',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'zbbs', index: 'zbbs',sortable:false,label:'在保笔数',searchoptions:{sopt:['eq ','ge','le']}},
                {name: 'errorDesc', index: 'errorDesc',sortable:false,label:'错误描述',searchoptions:{sopt:['bw']}},
                {name: 'existError', index: 'existError', sortable: false,hidden: true,label:'是否错误',search : false},
                {name: 'recordStatus', index: 'recordStatus', sortable: false,hidden: true,label:'是否忽略',searchoptions:{sopt:['eq']}}
            ],
            rowNum: 20,
            rowList: [20, 50, 100],
            pager: '#pager',
            imgpath: 'images',
            sortname: 'id',
            viewrecords: true,
            sortorder: "desc",
            autowidth:true,
            multiselect:true,
            jsonReader: {
                repeatitems : false,
                id: "id"
            },
//            beforeSelectRow: function (rowid, e) {
//                var $myGrid = $(this),
//                        i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
//                        cm = $myGrid.jqGrid('getGridParam', 'colModel');
//                return (cm[i].name === 'cb');
//            },
            onSelectRow : function(id) {
                if (id && id !== lastsel1) {
                    jQuery('#grid_tbl').jqGrid('restoreRow', lastsel1);
                    jQuery('#grid_tbl').jqGrid('editRow', id,  {
                        "keys" : true,
                        "aftersavefunc" : refreshList,
                    });
                    lastsel1 = id;
                }
            },
            gridComplete: function () {
                var ids = $("#grid_tbl").jqGrid('getDataIDs');
                for(i=0;i<ids.length;i++ ){
                    var obj =$("#grid_tbl").jqGrid("getRowData",ids[i]);
                    if(obj.existError=="Y"){
                        $("#"+ids[i]).find("td").css("background-color", "red");
                    }
                    if(obj.recordStatus=="2"){
                        jQuery("#grid_tbl").jqGrid('setSelection', ids[i]);
                    }
                }

                var businessTitle = "${config.businessTitle}".split(",");
                for(var i=0;i<businessTitle.length;i++){
                    jQuery("#grid_tbl").setGridParam().hideCol(businessTitle[i]);
                }
                if(businessTitle.length>0){
                    $("#grid_tbl").setGridWidth($(window).width()*0.99);
                }
            },
            editurl :"${ctx}/guarantee/editGuarantee",
            caption: "担保业务查询结果列表"
        });

        jQuery("#grid_tbl").jqGrid('navGrid', '#pager', {
            add: false,
            edit: false,
            del: false,
            search: false,
            refresh: false
        });
        $("#grid_tbl").jqGrid('navButtonAdd', '#pager', {
            caption: "隐藏/可见列",
            title: "选择列",
            onClickButton: function () {
                $("#grid_tbl").jqGrid('columnChooser',{
                    done : function (perm) {
                        if (perm) {
                            // "OK" button are clicked
                            this.jqGrid("remapColumns", perm, true);
                            $("#grid_tbl").setGridWidth($(window).width()*0.99);
                        } else {
                            // we can do some action in case of "Cancel" button clicked
                        }
                    }
                });
            }
        });
        $("#grid_tbl").jqGrid('navButtonAdd', '#pager', {
            caption: "忽略/还原",
            onClickButton: function () {
                var selectedRows = jQuery('#grid_tbl').jqGrid('getGridParam','selarrrow');
                if(selectedRows.length>0){
                    var checkedRows = "";
                    for (var x = 0; x < selectedRows.length; x++) {
                        var isDisabled = $('#jqg_grid_tbl_' + selectedRows[x]).is(':disabled');
                        if (!isDisabled) {
                            checkedRows=checkedRows+ selectedRows[x];
                            if(x!=selectedRows.length-1)
                            {
                                checkedRows=checkedRows+",";
                            }
                        }
                    }
                    if(checkedRows.length>0){
                        ignoreGuarantee(checkedRows);
                    }
                }

            }
        });

        $("#grid_tbl").jqGrid('navButtonAdd', '#pager', {
            caption: "保存列设置",
            onClickButton: function () {
                $.ajax({
                    url:'${ctx}/colMoldeConfig/saveConfig?d='+new Date().getTime(),
                    dataType:'json',
                    contentType:"application/x-www-form-urlencoded:charset=UTF-8",
                    data: {businessTitle:getHiddenName(),businessType:"27",id:colModelConfgiId},
                    success:function(data){
                        if (data.result = "true") {
                            colModelConfgiId=data.message;
                            $.prompt("保存成功");
                        } else {
                            $.prompt("保存失败");
                        }
                    }});
            }
        });

        jQuery("#grid_tbl").jqGrid('filterToolbar',{searchOperators : true});

    });

</script>